import pymysql
from . import config
import threading

_connections = {}


def get_connection():
    ident = threading.current_thread().ident
    if ident not in _connections:
        _connections[ident] = pymysql.connect(cursorclass=pymysql.cursors.DictCursor,
                                              **config.mysql_connect_str)

    return _connections[ident]


def execute(sql, cb=None, args=()):
    cursor = get_connection().cursor()
    try:
        n = cursor.execute(sql)
        if cb:
            return cb(cursor, args)
        return n
    except Exception as e:
        raise e
    finally:
        cursor.close()
        get_connection().commit()


def get_user(user):
    def get_user_info(cursor, args=()):
        return cursor.fetchone()

    return execute("select avatar, is_online from im_user where username='%s'" % user, get_user_info)


def get_users(exclude=()):
    sql = "select username, avatar, is_online from im_user"
    if exclude:
        sql += " where username not in {}".format(exclude)
    return execute(sql, lambda cursor, args: cursor.fetchall())
